<template>
	<view class="feng-week">
		<view class="yeardate">
			<view class="datebtn datebtnclose" @click="closedate">取消</view>
			<view class="flex">
				<view class="dateicon iconfont icon-fanhui1" @click="changeyear(1)"></view>
				<view class="datevalue">
					{{yearvalue}}
				</view>
				<view class="dateicon rotate iconfont icon-fanhui1" @click="changeyear(2)"></view>
			</view>
			<view class="datebtn text-blue" @click="subdate">确定</view>
		</view>
		<scroll-view scroll-y="true" style="height: 500rpx;" :scroll-with-animation="true" :scroll-into-view="'item'+weekindex1" @touchmove.stop="()=>{}">
			<view class="flex flex-wrap">
				<view class="dateitem solid" v-for="(item, index) in weeklist" :id="'item'+index"
					:class="{'activeitem': item.selects && item.year == saveyearvalue, 'activeitemindex': item.year == saveyearvalue && (item.date == weekvalue1)}"
					@click="selectWeek(item, index)" :key="index">
					<text style="display: block;">{{item.date}}</text>
					<text style="display: block;">{{item.week}}</text>
				</view>
			</view>
		</scroll-view>
	</view>
	
</template>

<script>
	
	Date.prototype.Format = function(fmt) { //需要JS格式化时间，后期做的时候方便使用   
		var o = {
			"M+": this.getMonth() + 1, //月份   
			"d+": this.getDate(), //日   
			"h+": this.getHours(), //小时   
			"m+": this.getMinutes(), //分   
			"s+": this.getSeconds(), //秒   
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度   
			"S": this.getMilliseconds() //毫秒   
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
					.length)));
		return fmt;
	};
	export default {
		data() {
			return {
				echo: false,
				weekindex1: '', // 第一个日期下标  重要 根据这个回显
				weekindex2: '', // 第二个日期下标  重要 根据这个回显
				weekvalue1: '', // 第一个日期value  因为日期太长 所以用下标代替 
				weekvalue2: '', // 第二个日期value  因为日期太长 所以用下标代替 
				weeklist: [], // 日期列表
				weekvaluelist: [], // 保存的日期列表
				saveyearvalue: '', // 保存的年份
				yearvalue: '' // 获取周的年份
			}
		},
		created() {
			// this.getvaluelistByTime()
		},
		methods: {
			// 根据时间回显
			getvaluelistByTime(time1, year) {
				var curDate = new Date();
				var newyear = new Date(curDate).getFullYear()
				this.echo = time1 && year ? true : false
				this.saveyearvalue = year ? year : newyear
				this.weekvalue1 = time1 ? time1 : ''
				this.yearvalue = year ? year.toString() : newyear
				this.weeklist = this.getAllWeekRange(this.yearvalue)
				var index1 = ''
				this.weeklist.forEach((item,index) => {
					if (time1 == item.date) {
						index1 = index
					}
				})
				setTimeout(()=>{
					this.weekindex1 = index1
				},100)
				if (index1 !== '') {
					this.getvalueList(index1, index1)
				}
			},
			closedate() {
				this.$emit("closedate")
			},
			subdate() {
				this.$emit("subdate", {
					date: this.weekvaluelist
				})
			},
			changeyear(type) {
				if (type == 1) {
					this.yearvalue--
				}
				else {
					this.yearvalue++
				}
				this.weeklist = this.getAllWeekRange(this.yearvalue)
				if (this.weekindex1 !== '') {
					this.getvalueList(this.weekindex1,this.weekindex1)
				}
			},
			selectWeek(item, index) {
				
				if (item.year !== this.saveyearvalue) {
					this.weekindex1 = ''
					this.weekvalue1 = ''
				}
				
				// 首先判断有没有点过第一个
				this.weekvaluelist = []
				
				this.weeklist.forEach(item => {
					item.selects = false
				})
				
				// 判断有没有选中过
				if (this.weekindex1 == index) {
					this.weekvalue1 = item.date
					this.weekindex1 = index
				}
				
				// 开始点击第一个日期
				this.weekvalue1 = item.date
				this.weekindex1 = index
				this.saveyearvalue = item.year
				this.echo = false
				this.getvalueList(this.weekindex1, this.weekindex1)
			},
			getvalueList(weekindex1, weekindex2) {
				for (let i = weekindex1; i <= weekindex2; i++) {
					this.weeklist[i].selects = true
					let objpush = Object.assign({}, this.weeklist[i])
					this.weekvaluelist.push(objpush)
				}
			},
			// 通过年获取 本年周数  year 年
			getWeekNum(year) {
				const firstDay = (new Date(parseInt(year), 0, 1)).getDay(), // 设置该年1.1星期
					endDay = (new Date(parseInt(year), 11, 31)).getDay(); // 设置该年12.31星期
			
				//该年最大周次.1.1.在周一到周四,则为该年第一周,否则为上年最后一周.
				const flag = ((firstDay >= 1 && firstDay <= 4) && (endDay == 0 || endDay == 4 || endDay == 5 || endDay ==
					6));
				// 1.1.和12.31.都在本年,则该年有53周,否则52周
				const maxWeek = flag ? 53 : 52;
				return maxWeek;
			},
			//通过年份、周数获取日期范围   year 年   weeks 周  getWeekRange(2019,12))--> 2019-03-18~2019-03-24
			getWeekRange(year, weekNum,type='') {
				const yearStart = new Date(parseInt(year), 0, 1), //设置该年1.1.
					firstDay = yearStart.getDay(); // 星期
				// 对1.1.所在周的前后几天特殊处理.
				const other = (firstDay >= 0 && firstDay <= 4) ? firstDay - 1 : firstDay - 8;
			
				//时间调整,得出要计算周的起/始时间.
				// 考虑距离当年1.1.的总天数
				let days = (parseInt(weekNum, 10) - 1) * 7 - other;
				// 一天时间的毫秒数
				let oneDay = 24 * 60 * 60 * 1000;
			
				// 当前周 第一天 离1/1/70的毫秒数.
				let dateInMs = oneDay * days + yearStart.getTime();
				//日期调整(设置1/1/70至今的毫秒数)
				const weekStart = new Date(dateInMs);
			
				//当前所选周最后一天处理,同上.
				let dateInMsE = oneDay * 6 + dateInMs;
				const weekEnd = new Date(dateInMsE);
			
				//月和日的处理,一位变两位,如:1->01.
				let month = weekStart.getMonth() + 1;
				month = (month < 10) ? "0" + month : month;
				let day = weekStart.getDate();
				day = (day < 10) ? "0" + day : day;
			
				let monthE = weekEnd.getMonth() + 1;
				monthE = (monthE < 10) ? "0" + monthE : monthE;
				let dayE = weekEnd.getDate();
				dayE = (dayE < 10) ? "0" + dayE : dayE;
				if(type == 'long'){
					return (weekStart.getFullYear() + "-" + month + "-" + day) + "~" + (weekEnd.getFullYear() + "-" + monthE + "-" + dayE)
				}else{
					return (month + "-" + day) + "~" + (monthE + "-" + dayE)
				}
				// return (month + day) + "-" + (monthE + dayE)
			},
			// 根据具体日期，获取当天所在周的周数
			getYearWeek(dateString) {
				var da = dateString; //日期格式2015-12-30
				//当前日期
				var date1 = new Date(da.substring(0, 4), parseInt(da.substring(5, 7)) - 1, da.substring(8, 10));
				//1月1号
				var date2 = new Date(da.substring(0, 4), 0, 1);
				//获取1月1号星期（以周一为第一天，0周一~6周日）
				var dateWeekNum = date2.getDay() - 1;
				if (dateWeekNum < 0) {
					dateWeekNum = 6;
				}
				if (dateWeekNum < 4) {
					//前移日期
					date2.setDate(date2.getDate() - dateWeekNum);
				} else {
					//后移日期
					date2.setDate(date2.getDate() + 7 - dateWeekNum);
				}
				var d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
				if (d < 0) {
					var date3 = (date1.getFullYear() - 1) + "-12-31";
					return getYearWeek(date3);
				} else {
					//得到年数周数
					var year = date1.getFullYear();
					var week = Math.ceil((d + 1) / 7);
					return week;
				}
			},
			
			// 获取每年 所有周的范围
			getAllWeekRange(year) {
				let weekNum = this.getWeekNum(year);
				let weeks = []
				for (let index = 1; index <= weekNum; index++) {
					let range = this.getWeekRange(year, index);
					let rangestr = "第" + index + "周";
					let startDate = this.getWeekRange(year, index,'long').split('~')[0];
					let endDate = this.getWeekRange(year, index,'long').split('~')[1];
					weeks.push({
						date: range,
						startDate:startDate,
						endDate:endDate,
						week: rangestr,
						year: year,
						value: index,
						select: false, // 前后值的判断依据
						selects: false,  // 区间值的判断依据
					});
				}
				return weeks
			},
			
		}
	}
</script>

<style lang="scss">
	.feng-week {
		width: 100%;
		height: 100%;
	}
	.yeardate {
		width: 100%;
		height: 90rpx;
		background: #FFFFFF;
		align-items: center;
		display: flex;
		justify-content: space-between;
	}
	.datebtn {
		padding: 0 30rpx;
	}
	.dateicon {
		margin: 0 40rpx;
		color: #999;
		&.rotate{
			transform: rotate(180deg);
		}
	}
	.dateitem {
		width: 20%;
		height: 120rpx;
		overflow: hidden;
		text-align: center;
		line-height: 60rpx;
		font-size: 20rpx;
	}

	.activeitem {
		background: rgba(79, 122, 252, .7);
		text{
			color: #fff;
		}
	}

	.activeitemindex {
		background: rgba(79, 122, 252, .7);
		text{
			color: #fff;
		}
	}
</style>
